package com.xiaobai.SynchrobizedLock;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;

import java.util.Vector;
import java.util.concurrent.locks.LockSupport;

@Slf4j(topic = "c.TestBiased")
public class TestBiased {


    static Thread t1, t2;

    public static void main(String[] args) throws InterruptedException {
        // 等待偏向锁启动
        Thread.sleep(5000);
        test4();
    }

    /*
    批量 biased 偏向锁
     */
    private static void test4() {
        Vector<Dog> list = new Vector<>();

        int loopNumber = 30;
        t1 = new Thread(() -> {
            for (int i = 0; i < loopNumber; i++) {
                Dog dog = new Dog();
                list.add(dog);
                synchronized (dog) {
                    log.debug("{}\t{}", i, ClassLayout.parseInstance(dog).toPrintable());
                }
            }
           synchronized (list){
                list.notify();
           }
        }, "t1");
        t1.start();
        t2 = new Thread(() -> {
         synchronized (list){
             try {
                 list.wait();
             } catch (InterruptedException e) {
                 throw new RuntimeException(e);
             }
         }
            log.debug("===============> ");
            for (int i = 0; i < loopNumber; i++) {
                Dog d = list.get(i);
                log.debug("{}\t{}", i, ClassLayout.parseInstance(d).toPrintable());
                synchronized (d) {
                    log.debug("{}\t{}", i, ClassLayout.parseInstance(d).toPrintable());
                }
                log.debug("{}\t{}", i, ClassLayout.parseInstance(d).toPrintable());
            }

        }, "t2");
        t2.start();

    }
}


